import store from "../index";
import { Mutation, Action, VuexModule, Module, getModule } from 'vuex-module-decorators'
import { LoginRequest, UserInfoEntity } from "/@/api/type/login";
import router from "/@/router";
import { PageEnum } from "/@/enums/pageEnum";
import { clearStorage, getStorage, setStorage } from "/@/utils/cache";
import { TOKEN_KEY, USER_INFO_KEY } from "/@/enums/cacheEnum";
// import { loginApi } from "/@/api/login";


@Module({name: 'UserManager', namespaced: true, dynamic: true, store})
class UserManager extends VuexModule{
  private UserInfo: UserInfoEntity | null = null;
  private AccessToken: string = '';

  get getUserInfo(): UserInfoEntity {
    return this.UserInfo || getStorage<UserInfoEntity>(USER_INFO_KEY) || {};
  }

  get getAccessToken(): string {
    return this.AccessToken || getStorage<string>(TOKEN_KEY);
  }

  @Mutation
  clearUserInfo(){
    this.UserInfo = null;
    this.AccessToken = '';
    clearStorage(USER_INFO_KEY);
    clearStorage(TOKEN_KEY)
  }

  @Mutation
  commitUserInfo(info: UserInfoEntity){
    this.UserInfo = info;
    this.AccessToken = info.accessToken;
    setStorage(USER_INFO_KEY, info);
    setStorage(TOKEN_KEY, info.accessToken, info.expireInSeconds);
  }

  @Action
  async login(params: LoginRequest): Promise<Boolean>{
    try {

      console.log('params', params);

      // const data = await loginApi.login(params);
      const data: UserInfoEntity = {
        accessToken: 'asdfasdf',
        expireInSeconds: 60 * 60,
        realName: '测试用户',
        userId: 1,
        userName: 'admin'
      }
      this.commitUserInfo(data);
      return true;
    }catch (e){
      console.error('e', e)
      return false;
    }
  }

  @Action
  logout(){
    router.push(PageEnum.BASE_LOGIN);
  }
}

export const userStore = getModule<UserManager>(UserManager)
